from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import SQLAlchemyError
from config import DBConfig


class DB:
    engine = create_engine(
        "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
            DBConfig.USERNAME, DBConfig.PASSWORD, DBConfig.HOST, DBConfig.PORT,
            DBConfig.DATABASE),
        echo=DBConfig.SQLALCHEMY_ECHO,
        pool_size=DBConfig.SQLALCHEMY_POOL_SIZE,
        pool_recycle=DBConfig.SQLALCHEMY_POOL_RECYCLE)

    def session(self):
        DbSession = sessionmaker(bind=self.engine, expire_on_commit=False)
        db_session = DbSession()
        return db_session

    def commit(self, db_session):
        try:
            db_session.commit()
        except SQLAlchemyError:
            db_session.rollback()
        finally:
            db_session.close()
